package org.bing.engine.common.graniteds;

import org.granite.config.flex.Destination;
import org.granite.context.GraniteContext;
import org.granite.messaging.service.ServiceException;
import org.granite.messaging.service.ServiceInvoker;
import org.granite.messaging.service.SimpleServiceFactory;
import org.granite.util.XMap;

import flex.messaging.messages.RemotingMessage;

public class MonitorServiceFactory extends SimpleServiceFactory {

    private static final long serialVersionUID = 1978;

    @Override
    public void configure(XMap properties) throws ServiceException {
        super.configure(properties);
    }

    @Override
    public ServiceInvoker<?> getServiceInstance(RemotingMessage request) throws ServiceException {
        String messageType = request.getClass().getName();
        String destinationId = request.getDestination();

        GraniteContext context = GraniteContext.getCurrentInstance();
        Destination destination = context.getServicesConfig().findDestinationById(messageType, destinationId);
        if (destination == null) {
            throw new ServiceException("No matching destination: " + destinationId);
        }
        String clzName = destination.getProperties().get("source");
        Object inst = SimpleBeanFactory.findService(clzName);
        return createMonitorServiceInvoker(destination, this, inst);
    }

    protected ServiceInvoker<?> createMonitorServiceInvoker(Destination destination, MonitorServiceFactory factory, Object bean) {
        return new MonitorServiceInvoker(destination, this, bean);
    }
}